Public Class SMSCollectionAdder

    Private Sub CursorWait(ByVal activate As Boolean)
        If activate = True Then
            Me.Cursor = Cursors.WaitCursor
        Else
            Me.Cursor = Cursors.Arrow
        End If
    End Sub
    Private Sub btnGetCollections_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetCollections.Click
        Me.checklistCollections.Items.Clear()
        CursorWait(True)
        On Error GoTo err_handler 'Resume Next                                'Some error handling
        Dim strserver, strsitecode As String
        Dim colcollections
        Dim objlocator, objsms
        Dim colsitedetails, inssitedetails, inscollection

        strserver = Me.txtSMSServer.Text                     'zieht sich den Servernamen
        strsitecode = ""

        objlocator = CreateObject("WbemScripting.SWbemLocator")
        objsms = objlocator.ConnectServer(strserver, "Root/SMS")            'connect to sms
        objsms.Security_.ImpersonationLevel = 3
        'Me.listLOG.Items.Add("Connecting to Root/SMS on " & strserver)

        colsitedetails = objsms.ExecQuery("select Machine, SiteCode from SMS_ProviderLocation where ProviderForLocalSite=True")
        For Each inssitedetails In colsitedetails
            strsitecode = inssitedetails.SiteCode
        Next
        'Me.listLOG.Items.Add("Connecting to Root/SMS/site_" & strSiteCode & " on " & strserver)
        objsms = objlocator.ConnectServer(strserver, "root/SMS/site_" + strsitecode)
        'Me.listLOG.Items.Add("Connected to " & strsitecode)

        colcollections = objsms.ExecQuery("Select CollectionID, Name from SMS_Collection ORDER BY CollectionID")
        For Each inscollection In colcollections
            'Me.treeCollections.Nodes.Add(inscollection.CollectionID & " - " & inscollection.Name)
            Me.checklistCollections.Items.Add(inscollection.CollectionID & vbTab & inscollection.Name)
        Next
        Me.listLOG.Items.Add("Successfully connected to SMS Server " & strserver)
        Me.picAddClientsToCollection.Enabled = True

        With My.Settings
            If strserver > 0 Then .SMSServer = strserver
        End With
        CursorWait(False)
        Exit Sub

err_handler:        
        Dim strErrCaption As String
        Dim ErrType As String

        ErrType = MsgBoxStyle.Information
        strErrCaption = "Connection failure"

        If Err.Number = "-2147217394" Then
            MsgBox("There is no SMS Server running on this machine or you are not allowed to query WMI", ErrType, strErrCaption)
        ElseIf Err.Number = "462" Then
            MsgBox("Can't connect to SMS Server '" & strserver & "'" & vbCrLf & vbCrLf & _
                    "Please make sure the server is online and you have sufficient rights to query the WMI of the server", ErrType, strErrCaption)
        End If
        CursorWait(False)
        Debug.Print("Line 1: " & Err.Source & vbCrLf & "Line 2: " & Err.Number)
    End Sub

    Private Sub picAddClientsToCollection_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles picAddClientsToCollection.Click
        On Error Resume Next

        Dim intClients, i, intSelectedCollections, j As Integer
        Dim colNewResources
        Dim insNewResource, instDirectRule, instColl, SMSContext
        Dim strSystem, strNewResourceID, strCollID As String
        SMSContext = ""
        instColl = ""
        strSystem = ""

        Dim strserver, strsitecode As String
        Dim colcollections
        Dim objlocator, objsms
        Dim colsitedetails, inssitedetails, inscollection

        strserver = Me.txtSMSServer.Text                     'zieht sich den Servernamen
        strsitecode = ""
        intClients = Me.txtSystemsToAdd.Lines.Length
        intSelectedCollections = Me.checklistCollections.CheckedIndices.Count
        Me.progAddotoCollectionProgress.Maximum = intClients
        i = 0

        If intSelectedCollections = 0 Then
            MsgBox("Please select at least one collection", MsgBoxStyle.Information, "No collection selected")
            Exit Sub
        End If

        objlocator = CreateObject("WbemScripting.SWbemLocator")
        objsms = objlocator.ConnectServer(strserver, "Root/SMS")            'connect to sms
        objsms.Security_.ImpersonationLevel = 3
        'Me.listLOG.Items.Add("Connecting to Root/SMS on " & strserver)

        colsitedetails = objsms.ExecQuery("select Machine, SiteCode from SMS_ProviderLocation where ProviderForLocalSite=True")
        For Each inssitedetails In colsitedetails
            strsitecode = inssitedetails.SiteCode
        Next
        'Me.listLOG.Items.Add("Connecting to Root/SMS/site_" & strsitecode & " on " & strserver)
        objsms = objlocator.ConnectServer(strserver, "root/SMS/site_" + strsitecode)
        Me.listLOG.Items.Add("Connected to " & strsitecode)

        Me.listLOG.Items.Add("Number of clients to add: " & intClients)
        Me.listLOG.Items.Add("Number of selected collections: " & intSelectedCollections)

        While intClients > i
            'Me.listLOG.Items.Add(Me.txtSystemsToAdd.Lines(i))
            strSystem = Me.txtSystemsToAdd.Lines(i)
            colNewResources = objsms.ExecQuery("SELECT ResourceId FROM SMS_R_System WHERE NetbiosName ='" & strSystem & "'")
            strNewResourceID = 0
            For Each insNewResource In colNewResources
                strNewResourceID = insNewResource.ResourceID
                'MsgBox(strNewResourceID)
            Next
            If strNewResourceID <> 0 Then               'if one exists crate a collection rule
                j = 0
                While intSelectedCollections > j
                    'Me.listLOG.Items.Add(Me.checklistCollections.CheckedItems.Item(j))
                    strCollID = Strings.Left(Me.checklistCollections.CheckedItems.Item(j), InStr(Me.checklistCollections.CheckedItems.Item(j), vbTab) - 1)  ' zieht sich die Collection ID und schreibt sie in strCollID
                    instColl = objsms.Get("SMS_Collection.CollectionID=" & """" & strCollID & """")
                    instDirectRule = objsms.Get("SMS_CollectionRuleDirect").SpawnInstance_()
                    instDirectRule.ResourceClassName = "SMS_R_System"
                    instDirectRule.ResourceID = strNewResourceID
                    instDirectRule.RuleName = "SMS Collection Adder - " & strSystem
                    instColl.AddMembershipRule(instDirectRule, SMSContext)
                    instColl.RequestRefresh(False)
                    Me.listLOG.Items.Add(strSystem & " added to " & instColl.Name)
                    j = j + 1
                End While
            Else
                Me.listLOG.Items.Add(strSystem & " not found.")     'otherwise display error
            End If
            i = i + 1
            Me.progAddotoCollectionProgress.PerformStep()
        End While
        MsgBox("All actions performed!", MsgBoxStyle.Information, "Finished")
        Me.progAddotoCollectionProgress.Value = 0
    End Sub

    Private Sub GetClients()
        Dim intClients, i As Integer
        intClients = Me.txtSystemsToAdd.Lines.Length

        i = 0
        While intClients > i
            Me.listLOG.Items.Add(Me.txtSystemsToAdd.Lines(i))
            i = i + 1
        End While
    End Sub

    Private Sub GetSelectedCollections()
        Dim intSelectedCollections, i As Integer
        i = 0
        intSelectedCollections = Me.checklistCollections.CheckedIndices.Count
        Me.listLOG.Items.Add("Number of selected collections: " & intSelectedCollections)
        While intSelectedCollections > i
            Me.listLOG.Items.Add(Me.checklistCollections.CheckedItems.Item(i))
            Me.listLOG.Items.Add(Strings.Left(Me.checklistCollections.CheckedItems.Item(i), InStr(Me.checklistCollections.CheckedItems.Item(i), vbTab)))
            i = i + 1
        End While
    End Sub

    Private Sub btnOpenLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenLog.Click
        If Me.listLOG.Visible = False Then
            Me.listLOG.BringToFront()
            Me.listLOG.Visible = True
            Me.btnOpenLog.Text = "Close Log"
        Else
            Me.listLOG.SendToBack()
            Me.listLOG.Visible = False
            Me.btnOpenLog.Text = "Open Log"
        End If
        'About.Show()
    End Sub

    Private Sub SMSCollectionAdder_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.txtSMSServer.Text = My.Settings.SMSServer
    End Sub

    Private Sub txtSMSServer_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSMSServer.TextChanged

    End Sub
    
End Class
